// src/components/ScatterLineChart.jsx
import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { validateData } from '../utils/dataConverter';

const ScatterLineChart = ({ initialData, chartStyle }) => {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const [xRange, setXRange] = useState({ min: 0, max: 20 }); // 初始横坐标范围

  // 图表初始化和更新
  useEffect(() => {
    if (!chartRef.current || !validateData(initialData)) return;

    // 计算横坐标范围（保持20单位跨度）
    const calculateXRange = () => {
      if (!initialData?.allSeries?.length) return { min: 0, max: 20 };
      
      // 获取所有系列中最新的时间戳
      const latestTimestamps = initialData.allSeries.map(series => {
        const lastPoint = series.line[series.line.length - 1];
        return lastPoint ? lastPoint.value[0] : 0;
      });
      
      const currentMax = Math.max(...latestTimestamps);
      return {
        min: Math.max(0, currentMax - 20), // 保持20单位跨度
        max: currentMax
      };
    };

    // 初始化函数
    const initChart = () => {
      if (!document.body.contains(chartRef.current)) return false;
      const existingInstance = echarts.getInstanceByDom(chartRef.current);
      if (existingInstance && !existingInstance.isDisposed) {
        chartInstance.current = existingInstance;
      } else {
        chartInstance.current = echarts.init(chartRef.current);
      }
      return true;
    };

    // 更新横坐标范围
    const newRange = calculateXRange();
    setXRange(newRange);

    // 安全设置选项函数
    const safeSetOption = (option) => {
      try {
        if (!chartInstance.current || chartInstance.current.isDisposed) {
          if (!initChart()) return;
        }
        chartInstance.current.setOption(option, true);
      } catch (error) {
        console.error('ECharts setOption error:', error);
      }
    };

    // 生成图表配置
    const option = generateChartOption(initialData, chartStyle, newRange);
    safeSetOption(option);

    // 响应式调整
    const handleResize = () => {
      if (chartInstance.current && !chartInstance.current.isDisposed) {
        chartInstance.current.resize();
      }
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [initialData, chartStyle]);

  // 组件卸载时清理资源
  useEffect(() => {
    return () => {
      if (chartInstance.current && !chartInstance.current.isDisposed) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  // 生成图表配置选项
  const generateChartOption = (data, style, range) => {
    const series = [];
    
    // 处理多系列数据
    if (data.multiSeries && data.allSeries) {
      data.allSeries.forEach((seriesData, index) => {
        // 散点图系列
        series.push({
          name: seriesData.seriesInfo.name,
          type: 'scatter',
          data: seriesData.line.map(point => point.value),
          symbolSize: 8,
          itemStyle: {
            color: getSeriesColor(index)
          },
          // 禁用散点动画
          animation: false
        });
        
        // 折线图系列
        series.push({
          name: `${seriesData.seriesInfo.name}趋势线`,
          type: 'line',
          data: seriesData.line.map(point => point.value),
          smooth: true,
          lineStyle: {
            width: 2,
            color: getSeriesColor(index)
          },
          showSymbol: false,
          // 彻底禁用动画
          animation: false
        });
      });
    }
    
    // 配置坐标轴（关键修改：动态横坐标范围）
    const axisOptions = {
      xAxis: {
        type: style.xScaleType || 'value',
        min: range.min, // 动态最小值
        max: range.max, // 动态最大值
        position: 'bottom',
        name: '时间序列',
        nameLocation: 'center',
        nameGap: 25,
        axisLine: { show: style.showBottomAxis },
        axisTick: { show: style.showBottomAxis }
      },
      yAxis: {
        type: style.yScaleType || 'value',
        position: 'left',
        name: '数值',
        nameLocation: 'center',
        nameGap: 40,
        axisLine: { show: style.showLeftAxis },
        axisTick: { show: style.showLeftAxis }
      }
    };
    
    return {
      // 全局禁用动画
      animation: false,
      
      title: {
        text: style.titleShow ? style.titleText : '',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const point = params[0].value;
          return `时间: ${point[0]}<br/>数值: ${point[1].toFixed(2)}`;
        }
      },
      legend: {
        data: series.map(s => s.name),
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: style.titleShow ? '12%' : '5%',
        containLabel: true
      },
      ...axisOptions,
      series
    };
  };
  
  // 为不同系列生成颜色
  const getSeriesColor = (index) => {
    const colors = [
      '#5470c6', '#91cc75', '#fac858', '#ee6666', 
      '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
    ];
    return colors[index % colors.length];
  };

  return (
    <div 
      ref={chartRef} 
      style={{ 
        width: '100%', 
        height: '100%',
        minHeight: '700px'
      }}
    />
  );
};

export default ScatterLineChart;